package javaUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.thoughtworks.xstream.XStream;

public class XStreamUtils {

	private static XStreamUtils instancia;

	private XStreamUtils() {

	}

	public static XStreamUtils getInstancia() {
		if (instancia == null)
			instancia = new XStreamUtils();
		return instancia;
	}

	// TODO: MEJORAR
	public File objectToXML(Object obj, String alias, String fileAbsPath)
			throws IOException {

		XStream stream = new XStream();
		//stream.alias(alias, obj.getClass());
		String xml = stream.toXML(obj);
		System.out.print(xml);
		stringToDom(xml, fileAbsPath);
		File f = new File(fileAbsPath);
		return f;
	}

	private static void stringToDom(String xmlSource, String fileAbsPath)
			throws IOException {
		java.io.FileWriter fw = new java.io.FileWriter(fileAbsPath);
		fw.write(xmlSource);
		fw.close();
	}
	
	// TODO: MEJORAR
		public Object XMLToObject(Object obj, String fileAbsPath)
				throws IOException {

			XStream stream = new XStream();
			InputStream is = new FileInputStream(fileAbsPath);
			
			if (is != null){
				obj = stream.fromXML(is, obj);
			}
			return obj;
		}

}
